package org.dinner.order.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.dinner.order.dao.BaseDAO;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class BaseDAOImpl<T> implements BaseDAO<T>  {
	
	@Autowired
	protected SessionFactory sessionFactory;

	public T add(T item) {
		sessionFactory.getCurrentSession().save(item);
		return item;
	}

	public List<T> list() {
		return sessionFactory.getCurrentSession().getNamedQuery(getQueryPrefix() + ".list").list();
	}

	public T getById(int id) throws ObjectNotFoundException {
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		Class<T> clazz = (Class<T>)type.getActualTypeArguments()[0];
		return (T) sessionFactory.getCurrentSession().load(clazz, id);
	}

	public void remove(int id) {
		T item = getById(id);
		
		if (item != null) {
			sessionFactory.getCurrentSession().delete(item);
		}
	}
	
	protected abstract String getQueryPrefix();

}
